<?php

namespace app\impl;

use app\common\lib\ZhyxBeanstalkd;
use app\common\lib\ZhyxMongo;
use app\common\model\BindDiseasePath;
use app\common\model\DiseasePath;
use app\common\model\DiseasePathBind;
use app\common\model\DiseasePatientTask;
use app\common\model\DiseaseTask;
use app\common\model\PatientInfo;
use app\interfaces\Task;
use app\common\model\PropagandaEducationHistory as PehModel;
use app\common\model\PushMessage as PmModel;
use MongoDB\BSON\ObjectId;
use think\facade\Log;

class TagDiseaseTask implements Task
{

    public function run(array $data, string $taskId): ?bool
    {

        $taskInfo = (new DiseasePatientTask())->where([["planList.plan_task_id", "=", new ObjectId($data["plan_task_id"]['$oid'])]])->find();


        if (!empty($taskInfo)) {
            #根据传过来的任务id，更新成进行中的状态
            $result = ZhyxMongo::getInstance()->setCollection("disease_patient_task")->updateOne(['planList.plan_task_id' => new ObjectId($data["plan_task_id"]['$oid'])], ['$set' => ['planList.$.plan_task_status' => 1, 'update_at' => time()]]);

            if ($result->getModifiedCount() > 0) {
                # 获取绑定的随访路径
                $bindDiseasePath = (new BindDiseasePath())->where([["id", "=", $taskInfo["bind_id"]]])->find();
                if (isset($bindDiseasePath["is_close"]) && (int)$bindDiseasePath['is_close'] === 1) {
                    return true;
                }

                if ($bindDiseasePath["step"] < $taskInfo["step_order"]) {
                    (new BindDiseasePath())->where("id", "=", $taskInfo["bind_id"])->save(["step" => $taskInfo["step_order"]]);
                }
                # 判断当前任务是否是轮训任务，如果是轮询任务计算下一个发布时间点
                if ($taskInfo["step_is_repeat"] === true) {
                    #计算新一轮的推送时间
                    $patientInfo = (new PatientInfo())->getPatientInfo($taskInfo["patient_id"]);
                    $maxPlanListIndex = count($taskInfo["planList"]) - 1;
                    print_r($taskInfo);exit();
                    $taskInfo = (new \app\common\business\DiseasePath())->calcPath($patientInfo, $taskInfo["id"], null, $taskInfo["planList"][$maxPlanListIndex]["plan_date"]);
                    if (!empty($taskInfo)) {
                        # 执行任务的分发
                        (new \app\common\business\DiseasePath())->pushTask([$taskInfo]);
                    }
                }
            }
        }
        return true;
    }
}